<template>
    <basic-container>
        <avue-crud :data="data"
                   :option="option"
                   :page="page"
                   @refresh-change="refreshChange"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @on-load="onLoad"
        >
            <!-- 是否显示插槽 -->
            <template slot-scope="{row}" slot="status">
                <el-switch @change="rowSwitchChange(row)"  v-model="row.status" active-value="ENABLE" inactive-value="DISABLE" active-color="#13ce66" nactive-color="#ff4949" />
            </template>

            <template slot-scope="{row,type,size}" slot="menu">
                <el-button :type="type" :size="size"  v-if="row.status=='LOCKED'" @click="review(row.id)" v-has="'/mall-cloud-system/mgr/getUserById'">审核</el-button>
                <el-button :type="type" :size="size" v-if="row.status=='ENABLE'" @click="stocksDetail(row)" v-has="'/mall-cloud-system/mgr/delete'">查看库存</el-button>
                <el-button :type="type" :size="size" v-if="row.status=='ENABLE'" @click="distribution(row)" v-has="'/mall-cloud-system/mgr/delete'">配货</el-button>
            </template>
        </avue-crud>

        <el-dialog title="审核线下店" :visible.sync="confirmDialog" append-to-body width="30%">
            <el-form :model="dialogForm">
                <el-form-item>
                    <el-button type="primary" :loading="loadReplyBtn" @click="reviewOffLineStore(dialogForm.userId,'ENABLE')" v-has="'/mall-cloud-system/mgr/reviewOffLineStore'">审核通过</el-button>
                    <el-button type="primary" :loading="loadReplyBtn" @click="reviewOffLineStore(dialogForm.userId,'REFUSE')" v-has="'/mall-cloud-system/mgr/reviewOffLineStore'">审核拒绝</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <el-dialog title="库存查看"  width="80%" :visible.sync="dialogVisibleB" @close="closeDrawer()">
            <avue-crud :option="optionB"  ref="crud" :data="resucedataB"  v-model="formB" :table-loading="loading"
                       :page="pageB" @refresh-change="refreshChangeB" @search-change="searchChangeB" @current-change="currentChangeB" @size-change="sizeChangeB">
            </avue-crud>
        </el-dialog>

        <!--配货-->
        <el-drawer :wrapperClosable="false" :visible.sync="drawerStocks" :with-header="false" size="70%">
            <div class="demo-drawer__header">
                <div class="drawerHeader">
                    <strong>配货</strong>
                </div>
            </div>
            <div class="demo-drawer__content">
                <avue-form ref="formGoods" v-model="objDistribution" :option="optionDistribution">
                    <template slot="goods">
                        <avue-crud ref="goodsCrud" :data="goodsList" :option="optionGoods" v-model="objGoods" :table-loading="goodsloading"
                                   :page="goodsPage" @selection-change="selectionChange" @refresh-change="refreshGoodsChange"
                                   @search-change="searchGoodsChange" @search-reset="searchGoodsReset" @current-change="currentGoodsChange"
                                   @size-change="sizeGoodsChange">
                            <template slot-scope="{row}" slot="goodsMainPhotoUrl">
                                <img :src="row.goodsMainPhotoUrl" style="width:50px;height:50px;" />
                            </template>
                        </avue-crud>
                    </template>

                    <template slot="goodsStock" >
                        <avue-crud ref="goodsStockCrud" :data="goodsStockList" :option="goodsStock" v-model="objGoodsStock"  >
                            <template slot-scope="{ row }" slot="distributionNum">
                                <el-input type="number" v-model="row.distributionNum" placeholder="请输入内容"></el-input>
                            </template>
                        </avue-crud>
                    </template>

                    <template slot="menuForm">
                        <el-button type="primary" @click="handleSubmit" :loading="load">保存</el-button>
                        <el-button @click="handleEmpty">关闭</el-button>
                    </template>
                </avue-form>
            </div>
        </el-drawer>

    </basic-container>
</template>
<script>
    var Dict = JSON.parse(localStorage.getItem("mall-dictionary")).content;

    import { getList, reviewOffLineStore, distributionSubmit } from "@/api/minmao/mgr/offLineStore.js";
    import { getStocksList } from "@/api/minmao/mgr/stocks";
    import { getListForOffLineStore } from "@/api/base/goods/goods";
    import { showGoodsStock } from '@/api/base/goods/goodsSku';

    export default {
        data() {
            return {
                offLineStoreId:'',//线下店id，配货提交时使用
                dialogVisibleB:false,
                loadReplyBtn:false,
                addLoad:false,
                confirmDialog:false,
                drawerStocks:false,
                goodsList: [],
                idList:[],
                objDistribution:{},
                optionDistribution: {
                    emptyBtn: false,
                    submitBtn: false,
                    column: [
                        {
                            prop: "goods",
                            span: 24,
                            formslot: true,
                        },
                        {
                            prop: 'goodsStock',
                            span: 24,
                            formslot: true,
                            display: true,
                        }
                    ]
                },
                optionGoods: {
                    header: false,
                    selection: true,
                    menu: false,
                    search: true,
                    border: true,
                    align:'center',
                    searchMenuSpan:6,
                    column: [{
                        label: "商品图片",
                        prop: "goodsMainPhotoUrl",
                        slot: true,
                        width:150,
                    }, {
                        label: "商品名称",
                        prop: "goodsName",
                        align:'left',
                        search: true,
                        searchSpan: 8,
                    }, {
                        label: "指定分类",
                        prop: "goodsClassId",
                        hide: true,
                        type: 'select',
                        dicUrl: '/base/goodsClass/listManage?classLevel=2',
                        dicMethod: 'post',
                        props: {
                            label: 'className',
                            value: 'id'
                        },
                        search: true,
                        searchSpan: 8,
                    }, {
                        label: "总库存",
                        prop: "stock",
                        width:100,
                        span: 24,
                    }]
                },
                objGoods: {},
                goodsloading: true,
                goodsPage: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                goodsQuery: {},
                goodsStockList: [],
                goodsStock: {
                    size: 'mini',
                    excelBtn: false,
                    addBtn: false,
                    delBtn: false,
                    editBtn: false,
                    columnBtn: false,
                    border: true,
                    header: false,
                    simplePage:true,
                    align: 'center',
                    rowKey: 'id',
                    menu: false,
                    column: [{
                        label: '商品名称',
                        prop: 'goodsName',
                        align:'left',
                    },
                        {
                            label: '规格属性',
                            width:200,
                            prop: 'skuName'
                        },
                        {
                            label: '配货数量',
                            prop: 'distributionNum',
                            width:150,
                            slot: true
                        }
                    ]
                },
                objGoodsStock: {},
                load:false,
                dialogForm:{
                    userId:""
                },
                box:false,
                editBox:false,
                formData:{
                    jobGroup:'',
                    jobName:'',
                    cronExpression:'',
                    jobDescription:''
                },
                option:{
                    size: 'mini',
                    editBtn:false,
                    addBtn:false,
                    delBtn:false,
                    height: 'auto',
                    // calcHeight: 380,
                    index: true,
                    page:false,
                    align:'center',
                    menuAlign:'center',
                    menuWidth: 100,
                    searchMenuSpan:6,
                    column:[
                        {
                            label:'账号',
                            prop:'account',
                            search: true,
                            rules: [{
                                required: true,
                                message: "请输入账号",
                                trigger: "blur"
                            }]
                        },
                        {
                            label:'姓名',
                            prop:'name',
                            rules: [{
                                required: true,
                                message: "请输入姓名",
                                trigger: "blur"
                            }]
                        },
                        {
                            label:'电话',
                            prop:'phone',
                            rules: [{
                                required: true,
                                message: "请输入电话",
                                trigger: "blur"
                            }]
                        },
                        {
                            label: '状态',
                            prop: 'status',
                            search: true,
                            type:'select',
                            dicData:Dict.managerStatusEnum,
                        },
                        {
                            label:'所属子公司',
                            prop:'parentName',
                            rules: [{
                                required: true,
                                message: "请输入类型",
                                trigger: "blur"
                            }]

                        }
                    ]
                },
                query: {},
                queryB: {},
                loading: true,
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                pageB: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                optionB: {
                    page: true,
                    size: 'mini',
                    tip: false,
                    border: true,
                    index: false,
                    rowKey: 'userId',
                    height: 'auto',
                    // calcHeight: 380,
                    addBtn: false,
                    delBtn: false,
                    editBtn: false,
                    viewBtn: false,
                    dialogType: 'dialog',
                    menuWidth: 240,
                    searchMenuSpan:6,
                    menu:false,
                    column: [
                        {
                            label: "线下店名称",
                            prop: "offlineStoreName",
                        },
                        {
                            label: '手机号',
                            prop: 'phone',
                            width: 120,
                            search: true,
                        },
                        {
                            label: "商品名称",
                            prop: "goodsName",
                            width:360
                        },
                        {
                            label: "sku名称",
                            prop: "skuName",
                        },
                        {
                            label: "sku编码",
                            prop: "skuCode",
                        },
                        {
                            label: "累计库存",
                            prop: "totalStocks",
                        },
                        {
                            label: "铺货数量",
                            prop: "distributionNum",
                            width: 180,
                        },
                        {
                            label: "现有库存",
                            prop: "nowStocks",
                            width: 180,
                        }
                    ]
                },
                data: [],
                resucedataB: [],
                formB:{},
            };
        },
        watch:{
            box(val){
                if(!val){
                    this.$nextTick(()=>{
                        this.$refs["ruleForm"].resetFields();
                    })
                    this.addLoad=false
                }
            },
            editBox(val){
                if(!val){
                    this.$nextTick(()=>{
                        this.$refs["ruleForm"].resetFields();
                    })
                    this.editLoad=false
                }
            },
        },
        methods: {
            // 点击页数
            currentChange (currentPage) {
                this.page.currentPage = currentPage;
            },
            // 点击页数
            sizeChange (pageSize) {
                this.page.pageSize = pageSize;
            },
            // 审核
            review(id){
                this.dialogForm.userId=id;
                this.confirmDialog=true;
            },
            //页面初始化请求管理员列表
            onLoad (page, params = {},done) {
                getList(page.currentPage,page.pageSize,Object.assign(params, this.query)).then(res=>{
                    if(done){
                        done();
                    }
                    this.data=res.data.data
                    this.page.total=res.data.count
                })
            },
            searchReset () {
                this.query = {};
                this.onLoad(this.page);
            },
            //审核线下店
            reviewOffLineStore(userId,status){
                this.loadReplyBtn=true
                reviewOffLineStore(userId,status).then((res)=>{
                    if(res.status==200){
                        this.loadReplyBtn=false
                        this.confirmDialog=false
                        this.onLoad(this.page);
                        this.$message({
                            type:'success',
                            message:'操作成功！'
                        })
                    }else if (res.status==500){
                        this.loadReplyBtn=false
                        this.confirmDialog=false

                    }
                })
            },
            // 搜索框
            searchChange(params,done) {
                this.page.currentPage=1
                this.query = params;
                this.onLoad(this.page, params,done);
            },
            refreshChange({page,searchForm}){
                this.onLoad(this.page);
            },
            //查看库存
            stocksDetail(row) {
                this.dialogVisibleB = true;
                this.queryB.offlineStoreId = row.id;
                this.onLoadB(this.pageB);
            },
            //查看库存弹框的取消
            closeDrawer() {
                this.dialogVisibleB = false;
                //清空搜索条件
                this.$refs.crud.searchReset();
            },
            refreshChangeB() {
                this.onLoadB(this.pageB);
            },
            searchChangeB (params,done) {
                this.query = params;
                this.onLoadB(this.pageB, this.query,done);
            },
            currentChangeB(currentPage) {
                this.pageB.currentPage = currentPage;
                this.onLoadB(this.pageB);
            },
            //  监听pageSize改变
            sizeChangeB (pageSize) {
                this.pageB.pageSize = pageSize;
                this.onLoadB(this.pageB);
            },
            //查看库存的页面加载
            onLoadB (pageB, params = {},done) {
                this.loading = true;
                getStocksList(pageB.currentPage, pageB.pageSize, Object.assign(params, this.queryB)).then(res => {
                    if(done){
                        done();
                    }
                    if(res.status==200){
                        this.loading = false;
                        this.resucedataB = [];
                        const data = res.data;
                        this.pageB.total = data.count;
                        this.resucedataB = data.data;
                        this.queryB = {};
                    }
                });
            },
            //打开配货页面
            distribution(row){
                this.goodsQuery = {
                    storeId: 1,
                    goodsStatus: 0
                };
                this.offLineStoreId = row.id;//线下店id，配货提交时使用
                this.onGoodsLoad(this.goodsPage)
                this.$nextTick(()=>{
                    this.drawerStocks = true;
                })
            },
            //选择商品的回调
            selectionChange(list) {
                this.idList = []
                if (list.length > 0) {
                    list.forEach((item, index) => {
                        this.idList[index] = item.id;
                    });
                    showGoodsStock(this.idList).then(res => {
                        if (res.data.code == 200) {
                            this.goodsStockList = res.data.data;
                        } else {
                            this.$message.error(res.data.message);
                        }
                    });
                } else {
                    this.idList = [];
                    this.goodsStockList = [];
                }
                console.log(this.idList)
            },
            refreshGoodsChange() {
                this.idList = []
                this.currentGoodsChange(1)
                this.$refs.goodsCrud.toggleSelection();
                this.onGoodsLoad(this.goodsPage);
            },
            searchGoodsChange(params,done) {
                this.idList = []
                this.$refs.goodsCrud.toggleSelection();
                this.goodsPage.currentPage = 1;
                params.goodsStatus = 0
                this.goodsQuery = params;
                this.onGoodsLoad(this.goodsPage, params,done);
            },
            searchGoodsReset() {
                this.idList = []
                this.$refs.goodsCrud.toggleSelection();
                this.onGoodsLoad(this.goodsPage);
            },
            currentGoodsChange(currentPage) {
                this.goodsPage.currentPage = currentPage;
                this.onGoodsLoad(this.goodsPage)
            },
            sizeGoodsChange(pageSize) {
                this.goodsPage.pageSize = pageSize;
                this.onGoodsLoad(this.goodsPage)
            },
            //配货页面保存
            handleSubmit() {
                this.load=true
                var data = {};
                console.log(this.idList)
                if (this.idList.length == 0) {
                    this.$message.error('至少选择一个商品进行配货');
                    this.load=false
                    return;
                }
                console.log(this.goodsStockList)
                for (let item of this.goodsStockList) {
                    //判断配货数量是否是大于等于0的整数
                    if(!this.testIsInteger(item.distributionNum)){
                        this.$message.error('配货数量应为大于0的整数');
                        this.load=false
                        return;
                    }
                }
                data = {
                    offLineStoreId: this.offLineStoreId,
                    goodsIds: this.idList,
                    goodsSkuList: encodeURI(JSON.stringify(this.goodsStockList))
                };
                distributionSubmit(data).then(res => {
                    if (res.data.code == 200) {
                        this.$message({
                            type: 'success',
                            message: '操作成功！'
                        });
                        this.handleEmpty()
                    } else {
                        this.$message.error(res.data.message);
                        this.$refs.goodsCrud.toggleSelection();
                        this.goodsStockList = [];
                        this.offLineStoreId = '';
                    }
                    this.load=false
                });
            },
            //关闭配货页面
            handleEmpty() {
                this.drawerStocks = false
                this.$refs.goodsCrud.toggleSelection();
                this.$refs.goodsCrud.searchReset();
                this.goodsStockList = [];
                this.goodsQuery={};
                this.offLineStoreId = '';
            },
            //加载商品列表
            onGoodsLoad(goodsPage, params = {},done) {
                params.goodsStatus = 0;
                this.goodsloading = true;
                getListForOffLineStore(
                    goodsPage.currentPage,
                    goodsPage.pageSize,
                    Object.assign(params, this.goodsQuery)
                ).then(res => {
                    if(done){
                        done();
                    }
                    this.goodsloading = false;
                    const data = res.data;
                    this.goodsPage.total = data.count;
                    this.goodsList = data.data;
                });
            },
            //校验是否是大于等于0的整数
            testIsInteger(val){
                let flag = false;
                var re = /^[0-9]*[1-9][0-9]*$/; //是否是大于或者等于0的整数
                if(re.test(val)){
                    flag = true;
                }
                else {
                    flag = false;
                }
                return flag;
            },
        }

    }
</script>
<style scoped>
    .drawerHeader {
        font-size: 20px;
        padding: 5px 20px;
    }
</style>
